

from rest_framework import serializers
from rest_framework.exceptions import ValidationError


from api import models


class UserModelSerializer(serializers.ModelSerializer):
    re_password = serializers.CharField(max_length=16, min_length=4, required=True, write_only=True)  # 因为 re_password 在表中没有，需要定义

    class Meta:
        model = models.User
        fields = ['username', 'password', 'mobile', 're_password', 'icon']
        extra_kwargs = {
            'username': {'max_length': 16},
            'password': {'max_length': 16, 'write_only': True},
            'icon': {'read_only': True}
        }

    def validate_mobile(self, data):
        if not len(data) == 11:
            raise ValidationError('手机号不合法')
        return data

    def validate(self, attrs):
        if not attrs.get('password') == attrs.get('re_password'):
            raise ValidationError('两次密码不一致')
        # 因为re_password不需要添加到数据库，所以要把它移除
        attrs.pop('re_password')
        return attrs

    def create(self, validated_data):
        # models.User.objects.create(**validated_data)  默认用的这个 密码不会加密
        user = models.User.objects.create_user(**validated_data)
        return user


# 反序列化类，往回返
class UserReadOnlyModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.User
        fields = ['username', 'icon']


class UserImageModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = ['icon']